package com.liry.custommvc.handler;

import com.alibaba.fastjson.JSON;
import com.liry.custommvc.HandlerAdapter;
import com.liry.custommvc.HttpRequestHandler;
import java.lang.reflect.Method;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author ALI
 * @since 2022/10/5
 */
@Component
public class RequestHandlerAdapter implements HandlerAdapter, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public boolean supports(Object controller) {
        return controller instanceof HttpRequestHandler;
    }

    @Override
    public Object handle(HttpServletRequest request, HttpServletResponse response, Object controller) throws Exception {
        HttpRequestHandler handler = (HttpRequestHandler) controller;
        Method method = handler.getMethod();
        Map<String, String[]> parameterMap = request.getParameterMap();

        Object[] resultParam = new Object[handler.getParamNameList().size()];
        for (int i = 0; i < handler.getParamNameList().size(); i++) {
            String paramName = handler.getParamNameList().get(i);
            String[] strings = parameterMap.get(paramName);
            if (strings != null && strings.length > 0) {
                resultParam[i] = strings[0];
            } else {
                resultParam[i] = null;
            }
        }
        Object invoke = method.invoke(applicationContext.getBean(handler.getBeanName()), resultParam);
        if (handler.isReturnView()) {
            return JSON.toJSONString(invoke);
        } else if (invoke instanceof String) {
            String str = (String) invoke;
            if (str.startsWith("forward:")) {
                request.getRequestDispatcher(str.split(":")[1]).forward(request, response);
            } else {
                response.sendRedirect(str);
            }
            return null;
        } else {
            return invoke;
        }
    }
}
